# app/api/v1/routes.py
from fastapi import APIRouter, HTTPException, status
from sqlalchemy.orm import Session

from app.core.dependencies import get_database
from .services import Services
from . import schemas

# 创建当前版本的路由器实例
router = APIRouter()
services = Services()

@router.get("/init_warehouses", response_model=schemas.ResponseAllLocationList)
async def init_warehouses(
    db: Session = get_database()
    ):
    """初始化数据库，并返回所有库位信息。"""

    try:
        location_info = services.init_warehouses(db)
        if location_info[0]:    
            return {
                "message": "数据获取成功",
                "data": [
                            {
                                "warehouse_1": location_info[1][0],
                                "warehouse_2": location_info[1][1]
                            }
                        ]
                    }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
                }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

@router.get("/read/warehouse/{warehouse_id}", response_model=schemas.ResponseLocationList)
async def read_warehouse(
    warehouse_id: int,
    db: Session = get_database()
    ):
    """读取数据库信息。根据指定库区号，获取指定仓库的全部库位信息。

    - **warehouse_id**: 仓库ID (1 或 2)
    """
    try:
        if warehouse_id == 1:
            location_info = services.get_warehouse(db=db, warehouse_id=1)
        elif warehouse_id == 2:
            location_info = services.get_warehouse(db=db, warehouse_id=2)

        if location_info[0]:
            return {
                "message": "数据获取成功",
                "data": location_info[1]
                }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
                }

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )
    
@router.post("/read/location_by_loc", response_model=schemas.ResponseLocationList)
async def read_location_by_loc(
    request: schemas.GetLocationByLoc,
    db: Session = get_database()
    ):
    """读取数据库信息。根据库位坐标, 获取指定位置信息。

    - **location**: 库位坐标 (格式: 'wh,x,y' - '库区,层,列')
    """
    try:
        location_info = services.get_location_by_loc(db, request.location)
        if location_info[0]:
            return {
                "message": "数据获取成功",
                "data": [location_info[1]]
                }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
                }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

@router.post("/read/location_by_pallet_id", response_model=schemas.ResponseAllLocationList)
async def read_location_by_pallet_id(
    request: schemas.GetLocationByPalletID,
    db: Session = get_database()
    ):
    """读取数据库信息。根据指定托盘号, 获取指定托盘号所在位置信息。

    - **pallet_id**: 托盘号 (任务号)
    """

    try:
        location_info = services.get_location_by_pallet_id(db, request.pallet_id)
        if location_info[0]:    
            return {
                "message": "数据获取成功",
                "data": [
                            {
                                "warehouse_1": location_info[1][0],
                                "warehouse_2": location_info[1][1]
                            }
                        ]
                    }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
                }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

    
@router.post("/read/location_by_status", response_model=schemas.ResponseAllLocationList)
async def read_location_by_status(
    request: schemas.GetLocationByStatus,
    db: Session = get_database()
    ):
    """读取数据库信息。根据指定库位状态, 获取所有指定状态的位置信息。

    - **status**: 库位状态

    库位状态: 
        0 - 可用库位, 
        1 - 存放托盘, 
        2 - 存放货物
    """
    
    try:
        location_info = services.get_location_by_status(db, request.status)
        if location_info[0]:    
            return {
                "message": "数据获取成功",
                "data": [
                            {
                                "warehouse_1": location_info[1][0],
                                "warehouse_2": location_info[1][1]
                            }
                        ]
                    }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
                }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

@router.post("/write/update_pallet_by_loc", response_model=schemas.ResponseLocation)
async def write_update_pallet_by_loc(
    request: schemas.UpdateLocationByLoc,
    db: Session = get_database()
    ):
    """修改数据库信息。通过位置ID修改托盘号, 并返回更新库位状态。

    - **location**: 库位坐标 (格式: 'wh,x,y' - '库区,层,列')
    - **pallet_id**: 托盘号 (任务号)
    """

    try:
        location_info = services.get_location_by_loc(
            db=db, 
            wh_location=request.location
            )
        if location_info[0]:
            new_location_info = services.update_pallet_by_loc(
                db=db, 
                wh_location=request.location,\
                pallet_id=request.pallet_id
                )
            if new_location_info[0]:
                return {
                    "message": "库位数据更新成功",
                    "data":[
                        {
                            "location": new_location_info[1]
                        }
                    ]
                }
            elif new_location_info[0] == False:
                return {
                    "message": f"{new_location_info[1]}",
                    "data": []
                }
            
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
            }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

@router.post("/write/delete_pallet_by_loc", response_model=schemas.ResponseLocation)
async def write_delete_pallet_by_loc(
    request: schemas.DeleteLocationByLoc,
    db: Session = get_database()
    ):
    """修改数据库信息。通过位置坐标删除托盘号, 并返回更新库位状态。
    
    - **location**: 库位坐标 (格式: 'wh,x,y' - '库区,层,列')
    """

    try:
        
        location_info = services.get_location_by_loc(
            db=db, 
            wh_location=request.location
            )
        if location_info[0]:
            new_location_info = services.delete_pallet_by_loc(
                db=db, 
                wh_location=request.location
                )
            if new_location_info[0]:
                return {
                    "message": "库位数据删除成功",
                    "data":[
                        {
                            "location": new_location_info[1]
                        }
                    ]
                }
            elif new_location_info[0] == False:
                return {
                    "message": f"{new_location_info[1]}",
                    "data": []
                }
        elif location_info[0] == False:
            return {
                "message": f"{location_info[1]}",
                "data": []
            }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )

@router.post("/tasks/inband", response_model=schemas.ResponseTaskList)
async def inband(
    request: schemas.TaskRequest,
    db: Session = get_database()
    ):
    """入库任务列表处理接口。
    
    - **stacker_location**: 堆垛机当前位置
    - **tasks**: 需要处理的任务列表
    """
    try:
        processed_data_info = services.task_inband(db, request)
        if processed_data_info[0]:
            processed_data = processed_data_info[1]
            return {
                "message": "数据接收成功",
                "total_tasks_received": len(request.tasks),
                "data": processed_data
            }
        elif processed_data_info[0] == False:
            processed_data = processed_data_info[1]
            return {
                "message": f"{processed_data}",
                "total_tasks_received": 0,
                "data": []
            }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )
    
@router.post("/tasks/outband", response_model=schemas.ResponseTaskList)
async def outband(
    request: schemas.TaskRequest,
    db: Session = get_database()
    ):
    """出库任务列表处理接口。

    - **stacker_location**: 堆垛机当前位置
    - **tasks**: 需要处理的任务列表
    """
    try:
        processed_data_info = services.task_outband(db, request)
        if processed_data_info[0]:
            processed_data = processed_data_info[1]
            return {
                "message": "数据接收成功",
                "total_tasks_received": len(request.tasks),
                "data": processed_data
            }
        elif processed_data_info[0] == False:
            processed_data = processed_data_info[1]
            return {
                "message": f"{processed_data}",
                "total_tasks_received": 0,
                "data": []
            }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )
    
@router.post("/tasks/move", response_model=schemas.ResponseMoveTaskList)
async def move(
    request: schemas.CarGoMoveRequest,
    db: Session = get_database()
    ):
    """库内转移任务列表处理接口。
    
    - **stacker_location**: 堆垛机当前位置
    - **tasks**: 需要处理的任务列表
    """
    try:
        processed_data_info = services.cargo_move(db, request)
        if processed_data_info[0]:
            processed_data = processed_data_info[1]
            return {
                "message": "数据接收成功",
                "total_tasks_received": len(request.tasks),
                "data": processed_data
            }
        elif processed_data_info[0] == False:
            processed_data = processed_data_info[1]
            return {
                "message": f"{processed_data}",
                "total_tasks_received": 0,
                "data": []
            }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"数据处理错误: {str(e)}"
        )